/**
 * 
 */
package uy.com.pzit.fpmundialmodel.manager;

import java.util.List;

import net.sf.ehcache.ObjectExistsException;

import org.springframework.beans.factory.annotation.Autowired;

import uy.com.pzit.fpmundialmodel.dao.PaisDAO;
import uy.com.pzit.fpmundialmodel.domain.Pais;
import uy.com.pzit.fpmundialmodel.response.MessageManager;
import uy.com.pzit.fpmundialmodel.response.PaisResponse;

/**
 * @author pferraz
 *
 */
public class PaisManager {

	@Autowired
	private PaisDAO paisDAO;
	
	public Pais addPais(Pais pais) {
		
		return paisDAO.addPais(pais);
	}

	public PaisResponse getPaisById(Integer id) {
		Pais pais=paisDAO.getPaisById(id);
		PaisResponse response=new PaisResponse();
		if(pais!=null){
			response.getPaises().add(pais);
			response.setMessage("");
			response.setSuccess(true);
		}else{
			response.setSuccess(false);
			response.setMessage(MessageManager.getInstance().getMessage("countryNotFound"));
		}
		return response;
	}

	
	/**
	 * @param paisDAO the paisDAO to set
	 */
	public void setPaisDAO(PaisDAO paisDAO) {
		this.paisDAO = paisDAO;
	}

	public PaisResponse getPaises() {
		List<Pais> paises=null;
		PaisResponse response=new PaisResponse();
		try{
			paises=paisDAO.getPaisesByOrder("nombre", "asc");
			response.setPaises(paises);
			response.setMessage("");
			response.setSuccess(true);
		}catch(ObjectExistsException e){
			response.setSuccess(false);
			response.setMessage(MessageManager.getInstance().getMessage("countriesNotFound"));
		}
		
		return response;
	}

	public PaisResponse getPaisByNombre(String nombre) {
		
		PaisResponse response=new PaisResponse();
		try{
			Pais pais=paisDAO.getPaisByNombre(nombre);
			response.getPaises().add(pais);
			response.setMessage("");
			response.setSuccess(true);
		}catch(ObjectExistsException e){
			response.setSuccess(false);
			response.setMessage(MessageManager.getInstance().getMessage("countryNotFound"));
		}
		return response;
	}

	public Pais updatePais(Pais pais) {
		return paisDAO.updatePais(pais);
	}

	/***
	 * Metodo encargado de actualizar la posicion del ranking FIFA de los paises
	 */
	public void updateRanking() {
		paisDAO.executePureQuery(new String[]{"SET @rownumber=0","UPDATE paises SET pos_en_ranking = (@rownumber:=@rownumber+1) ORDER BY ranking_fifa DESC"});
	}

	public PaisResponse getPaisesOrderByRanking() {
		List<Pais> paises=null;
		PaisResponse response=new PaisResponse();
		try{
			paises=paisDAO.getPaisesByOrder("posEnRanking", "asc");
			response.setPaises(paises);
			response.setMessage("");
			response.setSuccess(true);
		}catch(ObjectExistsException e){
			response.setSuccess(false);
			response.setMessage(MessageManager.getInstance().getMessage("countriesNotFound"));
		}
		return response;
	}

	
	
	

}
